<template>
	<view>
		<map class="map" :latitude="latitude" :longitude="longitude"></map>
		<view class="p-32 bg-white">
			<view class="flex address mt-20" @click="addressPopupShow = true">
				<image class="icon" src="../../static/location-1.png" mode=""></image>
				<view v-if="defaultAddress">{{ defaultAddress.address }}{{ defaultAddress.addressdesc }}</view>
				<view v-else>请选择地址</view>
			</view>
			<view class="user pb-20 border-b">
				<view class="size-30 gray-2">{{ defaultAddress.name }}</view>
				<view class="icon" @click="addressPopupShow = true">
					<image src="../../static/cae_list_btn_more@2x.png" mode=""></image>
					<view>地址簿</view>
				</view>
			</view>
			<scroll-view class="type-list border-b" scroll-x="true">
				<view class="item" :class="{ cur: TypeCur.indexOf(item.id) != -1 }" v-for="item in typeList"
					:key="item.id" @click="selectType(item.id)">
					<image :src="item.sortimage" mode=""></image>
					<view>{{ item.sortname }}</view>
				</view>
			</scroll-view>
			<view>
				<view class="size-30 gray-2 py-28">预估重量</view>
			</view>
			<view class="weight-list">
				<view class="item" :class="{ cur: weightCur == i }" v-for="(item, i) in weightList" :key="i"
					@click="weightCur = i">{{ item }}</view>
			</view>
			<view @click="dateShow = true">
				<view class="size-30 gray-2 py-28">预约上门时间(点此选择)</view>
				<u-input v-model="time" placeholder="请选择" disabled disabledColor="#ffffff"></u-input>
				<u-datetime-picker ref="datetimePicker" :show="dateShow" v-model="time" :minDate="curTime"
					@close="dateShow = false" @cancel="dateShow = false" @confirm="dateShow = false"
					mode="datetime"></u-datetime-picker>
			</view>
			<view class="btn-group" v-if="userInfo.mobile">
				<view @click="submit(1)" class="btn btn-1">公益赠送</view>
				<view @click="submit(2)" class="btn btn-2">立即下单</view>
			</view>
			<view class="btn-group" v-else>
				<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber($event, 1)"
					hover-class="button-hover" class="btn btn-1">公益赠送</button>
				<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber($event, 2)"
					hover-class="button-hover" class="btn btn-2">立即下单</button>
			</view>
		</view>
		<!-- 选择地址 -->
		<u-popup :show="addressPopupShow" mode="bottom" @close="addressPopupShow = false">
			<view class="empty" v-if="list.length == 0">
				<image src="../../static/empty.png" mode=""></image>
				<view>添加地址，预约你的回收天使～</view>
			</view>
			<view class="card">
				<view class="item" v-for="item in list" :key="item.id" @click="selectAddress(item)">
					<view class="flex-between">
						<view class="size-30">
							{{ item.name }}
							<text class="ml-30 gray-2">{{ item.mobile }}</text>
						</view>
						<view class="size-30 gray-9">{{ item.address }}{{ item.addressdesc }}</view>
					</view>
				</view>
			</view>
			<view class="btn-3 btn" @click="addAddress">
				<image src="../../static/address_btn_add_new@2x.png" mode=""></image>
				添加地址
			</view>
		</u-popup>
		<orderStatus :show="show" @closePopup="closePopup"></orderStatus>
	</view>
</template>

<script>
	var QQMapWX = require('../../common/qqmap-wx-jssdk.min.js');
	var qqmapsdk;
	import orderStatus from '../../components/onTakeOrder/onTakeOrder.vue';

	export default {
		components: {
			orderStatus
		},
		data() {
			return {
				show: false,
				addressPopupShow: false,
				list: '',

				latitude: '',
				longitude: '',
				defaultAddress: '',

				typeList: [],
				TypeCur: [],
				weightList: [],
				weightCur: 0,
				dateShow: false,
				curTime: Number(new Date()),
				time: '2024/01/01 00:00',

				baseUrl: '',
				userInfo: ''
			};
		},
		watch: {
			time(e) {
				var time = new Date(e);
				var y = time.getFullYear();
				var month = time.getMonth() + 1;
				var d = time.getDate();
				var h = time.getHours();
				var m = time.getMinutes();
				var s = time.getSeconds();
				month = month < 10 ? '0' + month : month;
				m = m < 10 ? '0' + m : m;
				d = d < 10 ? '0' + d : d;
				this.time = `${y}/${month}/${d} ${h}:${m}`;
			}
		},
		onLoad() {
			this.baseUrl = this.$tools.baseUrl;
			// 实例化API核心类
			qqmapsdk = new QQMapWX({
				key: '3SHBZ-L37KD-YBY4H-PJHZY-KW5BF-NLB3U'
			});
			this.getTypeList();
			this.getWeight();
		},
		onShareTimeline() {},
		onShareAppMessage() {},
		onShow() {
			if (!uni.getStorageSync('openid')) {
				uni.switchTab({
					url: '../user/user'
				});
				return;
			}
			this.userInfo = uni.getStorageSync('userInfo');
			this.getDefaultAddress();
			this.getList();
			this.$api
				.orderov({
					openid: uni.getStorageSync('openid')
				})
				.then(res => {
					if (res.code == 1) {
						if (res.data.status == 1) {
							this.show = true;
						}
					}
				});
		},
		methods: {
			getUserInfo() {
				this.$api
					.getUserInfo({
						openid: uni.getStorageSync('openid')
					})
					.then(res => {
						this.userInfo = res.data;
						uni.setStorageSync('userInfo', this.userInfo);
					});
			},
			// 获取用户手机号
			getPhoneNumber(e, type) {
				console.log(e);
				uni.login({
					provider: 'weixin',
					success: loginInfo => {
						console.log(loginInfo, 'loginInfo');
						this.$api
							.phoneAuth({
								openid: uni.getStorageSync('openid'),
								code: loginInfo.code,
								iv: e.detail.iv,
								encryptedData: e.detail.encryptedData
							})
							.then(res => {
								console.log(res);
								if (res.code == 1) {
									this.getUserInfo();
									this.submit(type);
								} else {
									uni.showToast({
										title: '获取失败，请重试',
										icon: 'none'
									});
								}
							});
					}
				});
			},
			closePopup() {
				this.show = false;
			},
			getLocation() {
				uni.getLocation({
					type: 'gcj02',
					success: res => {
						const latitude = res.latitude;
						const longitude = res.longitude;
						this.latitude = latitude;
						this.longitude = longitude;
						console.log(res);
						qqmapsdk.reverseGeocoder({
							location: {
								latitude,
								longitude
							},
							success: res => {
								console.log(res);
								this.locationAddress = res.result.address;
							},
							fail: err => {
								console.log(err);
							}
						});
					}
				});
			},
			// 获取地址列表
			getList() {
				this.$api
					.userAddress({
						openid: uni.getStorageSync('openid')
					})
					.then(res => {
						this.list = res.data;
						console.log(res);
					});
			},
			getTypeList() {
				this.$api.shopSort().then(res => {
					console.log(res);
					this.typeList = res.data;
				});
			},
			selectType(id) {
				console.log(id);
				let index = this.TypeCur.indexOf(id);
				console.log(index);
				if (index == -1) {
					this.TypeCur.push(id);
				} else {
					this.TypeCur.splice(index, 1);
				}
				console.log(this.TypeCur);
			},
			// 获取预估重量
			getWeight() {
				this.$api.weight().then(res => {
					console.log(res);
					this.weightList = res.data;
				});
			},
			// 获取默认地址
			getDefaultAddress() {
				this.$api
					.getDefaultAddress({
						openid: uni.getStorageSync('openid')
					})
					.then(res => {
						if (res.data) {
							this.defaultAddress = res.data;
							this.latitude = res.data.latitude;
							this.longitude = res.data.longitude;
						} else {
							this.getLocation();
						}
					});
			},
			addAddress() {
				this.addressPopupShow = false;
				uni.navigateTo({
					url: '../addAddress/addAddress?source=placeOrder'
				});
			},
			selectAddress(item) {
				this.defaultAddress = item;
				this.latitude = Number(item.latitude);
				this.longitude = Number(item.longitude);
				this.addressPopupShow = false;
			},
			submit(type) {
				this.$api
					.placeOrder({
						openid: uni.getStorageSync('openid'),
						sort: this.TypeCur.toString(),
						weight: this.weightList[this.weightCur],
						addresid: this.defaultAddress.id,
						appointment_at: this.time
					})
					.then(res => {
						if (res.code == 1) {
							this.$tools.toast('下单成功');
							if (type == 1) {
								setTimeout(() => {
									uni.navigateTo({
										url: '/pages/donate/donate'
									});
								}, 1000);
							} else {
								console.log("hello")
								setTimeout(() => {
									uni.navigateTo({
										url: '/pages/order/order',
										success() {
											var page = getCurrentPages().pop();
											if (page == undefined || page == null) return;
											page.onLoad();
										},
										fail(err) {
											console.log(err)
										}
									});
								}, 1000);
							}
						} else {
							this.$tools.toast(res.msg);
						}
					});
			}
		}
	};
</script>

<style lang="scss">
	.map {
		width: 100%;
		height: 588upx;
	}

	.address {
		border-radius: 16upx;
		margin-top: -16upx;
		padding: 32upx 0;

		.icon {
			width: 31upx;
			height: 37upx;
			min-width: 31upx;
			margin-right: 20upx;
		}
	}

	.user {
		display: flex;
		align-items: center;
		justify-content: space-between;

		.icon {
			font-size: 24upx;
			color: #3bb061;
			text-align: center;

			image {
				width: 40upx;
				height: 40upx;
			}
		}
	}

	.border-b {
		border-bottom: 1upx solid #efefef;
	}

	.type-list {
		white-space: nowrap;

		.item {
			display: inline-block;
			width: 138upx;
			height: 172upx;
			background: #ffffff;
			box-shadow: 0px 0px 10upx 0 rgba(96, 202, 130, 0.29);
			border-radius: 12upx;
			margin: 24upx 7upx;
			text-align: center;
			font-size: 28upx;
			color: #606060;
			line-height: 1.2;
			box-sizing: border-box;
		}

		.cur {
			color: #3bb061;
			border: 4upx solid #3bb061;
		}

		image {
			width: 100upx;
			height: 100upx;
			margin-top: 12upx;
		}
	}

	.weight-list {
		display: flex;
		// justify-content: space-between;
		flex-wrap: wrap;

		.item {
			margin-bottom: 14upx;
			text-align: center;
			font-size: 30upx;
			color: #c4c4c4;
			width: 216upx;
			line-height: 80upx;
			background: #ffffff;
			border-radius: 16upx;
			border: 2upx solid #c4c4c4;
		}

		.item:not(:nth-child(3n)) {
			margin-right: 12upx;
		}

		.cur {
			color: #3bb061;
			border: 2upx solid #3bb061;
		}
	}

	.btn-group {
		display: flex;
		justify-content: space-between;
		padding: 32upx 0;

		.btn {
			width: 320upx;
			border-radius: 12upx;
			font-size: 32upx;
			font-weight: 400;
			color: #ffffff;
			line-height: 88upx;
		}

		.btn-1 {
			background: #f3f3f3;
			color: #666666;
		}

		.btn-1:after {
			border: 0;
		}

		.btn-2 {
			background: #0b8f3a;
		}
	}

	.empty {
		text-align: center;
		margin: 100upx auto 120upx;

		image {
			width: 196upx;
			height: 196upx;
			margin-bottom: 36upx;
		}

		view {
			font-size: 28upx;
			font-weight: 400;
			color: #c4c4c4;
		}
	}

	.card {
		.item {
			background: #fff;
			padding: 28upx;
			margin-bottom: 16upx;
			border-radius: 12upx;

			.address {
				display: flex;

				.icon {
					margin-top: 4upx;
				}
			}

			.icon {
				min-width: 32upx;
				width: 32upx;
				height: 32upx;
			}

			.radio {
				transform: scale(0.9);
			}
		}
	}

	.btn-3 {
		width: 700upx;
		margin: 0 auto 30upx;
	}
</style>